package com.iweb.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class NettyServer {

    @Autowired
    private NoticeWebSocketHandler noticeWebSocketHandler;

    public void start(int port) {
        log.info("netty server is start...");
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 创建一个event用来处理新的连接、会话
        NioEventLoopGroup boos = new NioEventLoopGroup();
        // 创建一个event用来处理逻辑、读写
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // 配置服务器
        serverBootstrap.group(boos, worker)
                .channel(NioServerSocketChannel.class) // 设置通道
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        // 请求消息解码器
                        ch.pipeline().addLast(new HttpServerCodec());
                        // 将多个消息转换为单一的request或者response对象
                        ch.pipeline().addLast(new HttpObjectAggregator(65536));
                        // 处理WebSocket的消息事件
                        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
                        // 创建自己的webSocket处理器，就是用来编写业务逻辑的
                        ch.pipeline().addLast(noticeWebSocketHandler);
                    }
                }).bind(port);
    }
}